<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="openDialog">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="userList"
        style="width: 100%; margin-top: 20px"
        border
        stripe
      >
        <el-table-column prop="id" label="id"> </el-table-column>
        <el-table-column prop="username" label="用户名"> </el-table-column>
        <el-table-column prop="mobile" label="电话号码"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="120">
          <template slot-scope="scope">
            {{scope.row.create_time | DateFormat}}
          </template>
        </el-table-column>
        <el-table-column prop="mg_state" label="用户状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="handleTypeChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="role_name" label="用户角色"> </el-table-column>

        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="open_editForm(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="confirm_del(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="openSetRoleDialog(scope.row)"
              >
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :page-sizes="[1, 2, 5, 10]"
        :page-size="2"
        layout="total,sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="resetAddForm('addFormref')"
    >
      <!-- 内容主体区域 -->
      <el-form
        label-width="80px"
        :rules="addFormRules"
        ref="addFormref"
        :model="form"
      >
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input
            type="password"
            autocomplete="off"
            v-model="form.password"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input autocomplete="off" v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input autocomplete="off" v-model="form.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddForm('addFormref')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 编辑用户 -->
    <el-dialog title="编辑用户" :visible.sync="editDialog" width="50%">
      <!-- 内容主体区域 -->
      <el-form
        label-width="80px"
        ref="EditFormref"
        :model="editForm"
        :rules="editFormRules"
        @close="resetAddForm('EditFormref')"
      >
        <el-form-item label="用户ID" prop="id">
          <el-input v-model="editForm.id" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input autocomplete="off" v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input autocomplete="off" v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm('EditFormref')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialog" width="50%">
      <p>当前的用户名：{{ roleForm.username }}</p>
      <p>当前的角色名：{{ roleForm.role_name }}</p>
      <p>
        分配新的角色：<el-select v-model="setRoleId" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.rolename"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitNewRole(roleForm.id)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 4
      },
      userList: [],
      total: 0,
      // 获取所有的角色列表
      roleList: [],
      dialogVisible: false,
      editDialog: false,
      setRoleDialog: false,
      // 分配的新角色的ID
      setRoleId: '请选择',
      form: {
        password: '',
        username: '',
        email: '',
        mobile: ''
      },
      editForm: {
        id: '',
        email: '',
        mobile: '',
        rid: ''
      },
      roleForm: {},
      editFormRules: {
        mobile: [
          {
            required: true,
            message: '请输入电话号码',
            trigger: 'blur'
          },
          {
            min: 11,
            max: 11,
            message: '请输入正确的电话号码',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          }
        ]
      },
      addFormRules: {
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 10,
            message: '密码的长度应为3-10个字符'
          }
        ],
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getUserList()
  },
  computed: {},
  methods: {
    // 获取用户列表
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 确认是否删除
    confirm_del (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete('users/' + id)
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success('删除成功')
          this.getUserList()
        })
        .catch((err) => err)
    },
    // 监听 页码值改变事件
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    async handleTypeChange (obj) {
      const { data: res } = await this.$http.put(
        `users/${obj.id}/state/${obj.mg_state}`
      )
      console.log(res.data)
      if (res.meta.status !== 200) {
        obj.mg_state = !obj.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 打开新增用户弹框
    openDialog () {
      this.dialogVisible = true
    },
    // 提交新增的表单
    submitAddForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 解构赋值 await async化简promise
          const { data: res } = await this.$http.post('users', this.form)
          if (res.meta.status !== 201) {
            this.$message.error(res.meta.msg)
            this.dialogVisible = false
            return false
          }
          this.$message.success('添加用户成功')
          this.dialogVisible = false
          this.getUserList()
        } else {
          this.$message.error('添加用户失败！')
          this.dialogVisible = false
          return false
        }
      })
    },
    // 重置表单
    resetAddForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 编辑用户回显数据
    async open_editForm (id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查无此用户')
      }
      this.editForm = res.data
      this.editDialog = true
    },
    // 提交编辑用户信息
    async submitEditForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.put(
            'users/' + this.editForm.id,
            {
              email: this.editForm.email,
              mobile: this.editForm.mobile
            }
          )
          console.log(res, this.editForm)
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.editDialog = false
          this.$message.success('用户信息修改成功')
          this.getUserList()
        } else {
          this.dialogVisible = false
          return this.$message.error('用户信息修改失败')
        }
      })
    },
    // 打开角色分配弹框
    async openSetRoleDialog (user) {
      this.roleForm = user
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      const allRole = res.data
      allRole.forEach((item) => {
        this.roleList.push({
          id: item.id,
          rolename: item.roleName
        })
      })
      console.log(this.roleList)
      this.setRoleDialog = true
    },
    // 分配新的角色
    async submitNewRole (userId) {
      console.log(userId, this.setRoleId)
      const { data: res } = await this.$http.put(`users/${userId}/role`, {
        rid: this.setRoleId
      })
      if (res.meta.status !== 200) {
        return this.$message.error('设置角色失败！')
      }
      // 刷新页面
      this.getUserList()
      // 隐藏弹框
      this.setRoleDialog = false
    }
  }
}
</script>
<style lang="less" scoped>
.top-form {
  display: flex;
  width: 500px;

  .el-button {
    margin-left: 20px;
  }
}

.el-pagination {
  margin-top: 15px;
}
</style>
